package com.bigevent.interceptors;

import com.bigevent.utils.JwtUtil;
import com.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //实现登录才能访问的拦截器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的令牌（token）
        String token = request.getHeader("Authorization");
        //验证令牌
        try {
            //从Redis中获取token
            //创建Redis操作集
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            String redisToken = ops.get(token);
            if(redisToken == null){
                //token已经失效
                throw new RuntimeException();
            }
            //如果能拿到载体信息
            Map<String,Object> claims = JwtUtil.parseToken(token);
            //使用ThreadLocal将信息保存
            ThreadLocalUtil.set(claims);
            return true;//拦截器返回true表示放行
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除ThreadLocal中保存的数据，防止内存溢出
        ThreadLocalUtil.remove();
    }
}
